//
//  NSArrayAdditions.m
//  MailDelivery
//
//  Created by Dante Palacios on 30/08/09.
//  Copyright 2009 Dante Palacios. All rights reserved.
//

#import "NSArrayAdditions.h"

#import "MessageAddressee.h"
#import "NSStringAdditions.h"

#import "Funtions.h"


@implementation NSArray(NSArrayMailDeliveryAdditions)

+ (NSArray *)arrayByExtractingAddressesFromArray:(NSArray *)array validate:(BOOL)shouldValidateAddresses;
{
	NSMutableArray *result = [NSMutableArray array];
	for (id <MessageAddressee> obj in array) 
	{
		if (![obj respondsToSelector:@selector(address)]) continue;
		
		NSString *address = [obj address];
		if (!address.length) continue;
		
		if (shouldValidateAddresses && !IsValidEmail(address)) continue;
		
		[result addObject:address];
	}
	
	return result;
}

- (NSArray *)arrayByExtractingAddresses 
{
	return [NSArray arrayByExtractingAddressesFromArray:self validate:NO];
}

- (NSString *)componentsJoinedAsRecipients
{
	NSMutableString	*recipients = [NSMutableString string];
	for (id <MessageAddressee> obj in self) 
	{
		if (![obj respondsToSelector:@selector(address)]) continue;
		
		NSString *address = [obj address];
		if (!address.length) continue;
		
		[recipients appendString:[NSString stringWithFormat:@"RCPT TO:<%@>\r\n", address]];
	}
	
	return (NSString *)recipients;
}

@end